package com.hns.can.base.web;

import com.hns.can.base.entity.SysFieldValueRegisterEntity;
import com.hns.can.base.entity.SysRoleEntity;
import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.base.entity.SysUserRoleEntity;
import com.hns.can.base.service.SysAuthorityFuncService;
import com.hns.can.base.service.SysRoleService;
import com.hns.can.base.service.SysUserService;
import com.hns.can.base.vo.UserRoleVo;
import com.hns.can.common.domain.GridPage;
import com.hns.can.common.domain.ReturnResult;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.web.BaseController;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 角色信息controller
 * @author:zhangyu
 * @email:zhangyu2222z@sina.cn
 * @version Revision 2.0.0
 */
@Controller
@RequestMapping("/sysRole")
public class SysRoleController extends BaseController{
    
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysAuthorityFuncService sysAuthorityFuncService;
    
//    /**
//     * @author:zy
//     * @email:zhangyu2222z@sina.cn
//     * @创建日期:May 19, 2014
//     * @功能说明：角色列表页
//     */
//    @RequestMapping("/sysRoleList")
//    public ModelAndView sysRoleList() throws Exception {
//        return new ModelAndView("/system/sysRoleList", "command", new SysRoleEntity());
//    }
    
    /**
     * 获取角色信息
     * @return list
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getSysRoleList")
    @ResponseBody
    public Object getSysRoleList() {
        List<SysRoleEntity> sysRoleList = sysRoleService.findAll();
        return this.getReturnResult(sysRoleList);
    }
    
    /**
     * 通过角色名获取角色
     * @param roleName 角色名称
     * @return 角色list
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getSysRoleByName")
    @ResponseBody
    public Object getSysRoleByName(@RequestParam(value="roleName",required=false) String roleName) throws Exception {
        SysUserEntity user = getCurrentUser().getUser();

        List<BaseEntity> sysRoleList = sysRoleService.getSysRoleByName(roleName,user.getCorpId(),user.getId(), user.getRoleType());
        return this.getReturnResult(sysRoleList);
    }
    
    /**
     * 获取角色对应用户
     * @param vo 用户角色vo
     * @return 用户信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getUserPageByUserRoleVo")
    @ResponseBody
    public Object getUserPageByUserRoleVo(UserRoleVo vo) throws Exception {
        String roleId = vo.getRoleId();
        if(PubUtil.isEmpty(roleId)){//如果角色id为空返回
            throw new BusinessException(MsgType.WARN.getFlag(), "角色不存在");
        }
        //分页参数对象
        Pagination page = sysRoleService.getPageSysUserEntityList(vo);//获取翻页数据
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    
    /**
     * 获取没有该角色对应的用户
     * @param vo 用户角色vo
     * @return 未分配角色的用户
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getUnkownUserPageByUserRoleVo")
    @ResponseBody
    public Object getUnkownUserPageByUserRoleVo(UserRoleVo vo, HttpServletRequest request) throws Exception {
        //分页参数对象
        if(PubUtil.isEmpty(vo.getRoleId())){//未选择角色或角色为空则不查询
        	throw new BusinessException(MsgType.WARN.getFlag(), "请选择角色");
        }
        Pagination page = sysRoleService.getPageUnknowUserList(vo, this.getCurrentUser().getUser());
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    
    /**
     * 添加角色
     * @param entity 角色信息
     * @return 操作返回信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/saveSysRole")
    @ResponseBody
    public Object saveSysRole(@ModelAttribute("sysRoleEntity") SysRoleEntity entity) throws Exception{
        //校验角色名和角色编码是否重复
//        validateRepeat(entity,"sysRole.addCheckRoleInfoRepeat");
        //设置id为空，方便hibernate为其注入主键id
        entity.setId(UtilString.getUUID());
        sysRoleService.saveSysRole(entity);
        //#upt by jeffxu(字段权限) 取父级角色拥有的字段权限分配给角色
        //TODO
//        sysAuthorityFuncService.addParentFieldDataToRole(entity.getId(), entity.getParentRoleId());
        //默认保存父角色的资源权限
        List<SysFieldValueRegisterEntity> list = sysAuthorityFuncService.getCheckedAccessResData(entity.getParentRoleId());
        if(PubUtil.isNotEmpty(list)){
        	String[] fieldValueIds = new String[list.size()];
        	for(int i=0;i<list.size();i++){
        		fieldValueIds[i] = list.get(i).getId();
        	}
        	sysAuthorityFuncService.saveAccessResAuthority(entity.getId(), fieldValueIds);
        }
        //保存父角色的字段权限
        sysAuthorityFuncService.addParentFieldDataToRole(entity.getId(), entity.getParentRoleId());

//        return entity;
        return this.getReturnResult(entity);
    }
    
    /**
     * 编辑角色
     * @param entity 角色信息
     * @param userIds 用户id
     * @return 操作返回信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/updateSysRole")
    @ResponseBody
    public Object updateSysRole(@ModelAttribute("sysRoleEntity") SysRoleEntity entity, 
        @RequestParam(value = "userIds",required = false) String[] userIds) throws Exception{
        //校验角色名和角色编码是否重复
//        String validate = validateRepeat(entity,"sysRole.editCheckRoleInfoRepeat");

        Set<SysRoleEntity> set_role = this.getCurrentUser().getSet_role();
        sysRoleService.updateSysRole(entity, userIds, set_role);
//        if(validate.equals("true")){
//        }else{
//        	throw new BusinessException(MsgType.WARN.getFlag(), "角色编码或角色名已经存在");
//        }
        return this.getReturnResult(entity);
    }
    
    /**
     * 删除角色
     * @param id 角色id
     * @return 操作返回信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/delSysRole")
    @ResponseBody
    public Object delSysRole(@RequestParam(value = "id") String[] id) throws Exception {
        SysUserEntity user = getCurrentUser().getUser();
        sysRoleService.deleteSysRole(user, id);
        return this.getReturnResult();
    }
    
    /**
     * 添加用户角色关系
     * @param roleId 角色id
     * @param userIds 用户id
     * @return 操作返回信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/saveUserRole")
    @ResponseBody
    public Object saveUserRole(
        @RequestParam("roleId")String roleId,@RequestParam("userIds")String[] userIds){
        sysRoleService.saveUserRole(roleId,userIds);
        return getReturnResult();
    }
    
    
    /**
     * 删除指定角色对应的用户关系
     * @param roleId 角色id
     * @param userIds 用户id
     * @return 操作返回信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @ResponseBody
    @RequestMapping("/deleteUserRole")
    public Object deleteUserRole(
        @RequestParam("roleId")String roleId,@RequestParam("userIds")String[] userIds){
        sysRoleService.deleteUserRole(roleId,userIds);
        return getReturnResult();
    }
    
    /**
     * 校验角色名和角色编码是否重复
     * @param entity 角色信息
     * @param statments 操作语句
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    private String validateRepeat(SysRoleEntity entity,String statments) throws Exception{
        String validInfo = sysRoleService.validateRepeat(entity,statments);
        if(validInfo.length()>0){
//            throw new BusinessException(MsgType.ERROR.getFlag(), "您输入的"+validInfo+"已经存在！");
            return "您输入的"+validInfo+"已经存在！";
        }
        else return "true";
    }
    
    /**
     * 获取用户拥有的角色
     * @return 角色list
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getRoleIdsByUserId")
    @ResponseBody
    public Object getRoleIdsByUserId() throws Exception {
        SysUserEntity user = getCurrentUser().getUser();
        List<SysUserRoleEntity> list = sysUserService.getRoleIdsByUserId(user.getId());
        return this.getReturnResult(list);
    }
    
}
